#include "maininterfacewidget.h"
#include "ui_maininterfacewidget.h"
#include "user.h"
#include "addfriendsender.h"
//#include "addfriendsender.cpp"



MainInterfaceWidget::MainInterfaceWidget(QWidget *parent, user userSelf)
    : QWidget(parent)
    , ui(new Ui::MainInterfaceWidget)
{
    ui->setupUi(this);
    //connect()
    qDebug() << "userSelf:" << userSelf.getUserName();
    //websocket传输代码
    this->userSelf = userSelf;
    socket = new QWebSocket();//新建websocket
    QUrl url("ws://101.43.168.188:19999/slimarveous/ws");
    QUrlQuery query;//在query里面添加id token两个信息
    query.addQueryItem("id",userSelf.getUserId());
    query.addQueryItem("token",userSelf.getUserPassword());
    url.setQuery(query);
    socket->open(url);
    //连接到server
    QObject::connect(socket, &QWebSocket::connected,[=]() {
        qDebug() << "WebSocket connected";
    });
    //断开链接
    QObject::connect(socket, &QWebSocket::disconnected, [=]() {
        qDebug() << "WebSocket disconnected";
    });
    //获取信息
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message) {
        qDebug() << "Received message:" << message;
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
        //类型为chat
        if (type == "chat") {
          QString receivedContent = obj.value("content").toString();
          qDebug() << "Received chat message:" << receivedContent;
          ui->dialogTextBrowser->append(receivedContent);//对话双方均在线直接显示
        }
        //类型为未读消息
        else if (type == "pull_chat")
        {
            //将未读消息json文件转化成map
            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray ucMsg = pullChatMap.value("uc_messages").toJsonArray();
            for(int i = 0; i < ucMsg.size(); i++)
            {
                QJsonObject ucJsonObj = ucMsg.at(i).toObject();
                qDebug() << "这里是未读信息： " << ucJsonObj;
                QVariantMap messageMap = ucJsonObj.toVariantMap();
                QMap senderMap = messageMap.value("sender").toMap();
                QVariant sender = senderMap.value("username");
                qDebug() << "sender信息111" << sender;
                QString ucMsgContent = ucJsonObj.value("content").toString();
                qDebug() << "sender信息222：" << sender.toString();
                ui->dialogTextBrowser->append(sender.toString()+": "+ucMsgContent);//对话框中添加信息
            }

        }
        //类型为加好友
        else if (type == "add_friend_fail_or_success")
        {
          QString newFriendName = obj.value("name").toString();
          qDebug() << "User joined:" << newFriendName;
        }
    });
    connect(ui->addfriendsender,&QPushButton::clicked,this, &MainInterfaceWidget::addfriendsender_clicked);

}

MainInterfaceWidget::~MainInterfaceWidget()
{
    delete ui;
}


void MainInterfaceWidget::on_btn_send_main_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
//    qDebug() << "sender信息:" << Sender.username + Sender.id;
    //get content
    QString sendContent = ui->messageSendTextEdit->toPlainText();//传输服务器
    QString receiverId = ui->receiverId->text();
    receiverId.toLongLong();//id转化为long long
    //connect to server

    //sender信息
    QJsonObject senderValue{
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", ""},
        {"gender", Sender.gender.toInt()}
    };
    //receiver信息
    QJsonObject receiverValue{
        {"id", receiverId.toLongLong()},
        {"username", ""},
        {"photo", ""},
        {"gender", 1}
    };
    //发送的信息
    QJsonObject json{
        {"sender",senderValue},
        {"receiver", receiverValue},
        {"time", ""},
        {"type", "chat"},
        {"content", sendContent},
        {"is_photo","0"}
    };

    QJsonDocument doc(json);

    QByteArray data = doc.toJson(QJsonDocument::Compact);
    //qDebug() << "doc:" << doc << "data:" << data;

    socket->sendTextMessage(data);
    ui->dialogTextBrowser->append("me: "+ sendContent);
    ui->messageSendTextEdit->clear();
}


void MainInterfaceWidget::on_btn_clear_main_clicked()
{
    ui->messageSendTextEdit->clear();
}

void MainInterfaceWidget::addfriendsender_clicked()
{
    this->close();
    qDebug()<<"dhjksdfj";
    addfriendsender *afs = new addfriendsender(nullptr, userSelf);
    afs->show();
}
